package org.xxpay.pay.channel.yipay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

@Service
public class YipayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(YipayPayNotifyService.class);
    private static final String logPrefix = "【处理"+ YipayConfig.CHANNEL_NAME+"支付回调】";

    @Override
    public String getChannelName() {
        return YipayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理{}支付回调通知 ======", getChannelName());
        HttpServletRequest request = (HttpServletRequest) notifyData;
        JSONObject retObj = buildRetObj();
        Map<String, String> payContext = new HashMap();

        String respString = YipayConfig.RETURN_VALUE_ERROR;
        try {
            PayOrder payOrder = verifyPayParams(request, payContext);
            if( payOrder == null ) { //验证参数失败
                retObj.put(PayConstant.RESPONSE_RESULT, YipayConfig.RETURN_VALUE_ERROR);
                return retObj;
            }
            //订单已经支付完成
            if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
                retObj.put(PayConstant.RESPONSE_RESULT, YipayConfig.RETURN_VALUE_SUCCESS);
                return retObj;
            }
            //上游通知 状态
            String channelOrderNo = payContext.get("queryId"); //上游订单号

            int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), channelOrderNo);
            if (updatePayOrderRows != 1) {
                _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
                return retObj;
            }
            _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

            // 业务系统后端通知
            baseNotify4MchPay.doNotify(payOrder, true);
            _log.info("====== 完成处理{}支付回调通知 ======", getChannelName());
            respString = YipayConfig.RETURN_VALUE_SUCCESS;
        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
        }
        retObj.put(PayConstant.RESPONSE_RESULT, respString);
        return retObj;
    }

    /**
     * 验证通知参数
     * @return
     */
    public PayOrder verifyPayParams(HttpServletRequest request, Map<String, String> payContext) {
        BufferedReader reader = null;
        String line;
        String responseString = null;
        try {
            reader = request.getReader();
            StringBuffer inputString = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            responseString = inputString.toString();
        } catch (Exception e) {
            _log.error(e, logPrefix + "接收数据异常");
        } finally {
            if(reader != null) try{
                reader.close();
            }catch (Exception e) {
                _log.error(e, "");
            }
        }
        _log.info("{}通知参数=>{}", logPrefix, responseString);

        if(StringUtils.isBlank(responseString)) {
            return null;
        }

        JSONObject resObj = JSONObject.parseObject(responseString);

        // 校验结果是否成功
        String trade_no = resObj.getString("trade_no");		            // 上游订单号
        String out_trade_no = resObj.getString("out_trade_no");		    // 商户订单号
        String total_fee = resObj.getString("total_fee");                      // 实际支付金额
        String tradingfee = resObj.getString("tradingfee");                      // 手续费
        String paysucessdate = resObj.getString("paysucessdate");                  // 支付成功时间
        String sign = resObj.getString("sign"); 		                    // 签名

        _log.info("[{}]trade_no={}, out_trade_no={}, total_fee={}, tradingfee={}, paysucessdate={}, sign={}",
                logPrefix, trade_no, out_trade_no, total_fee, tradingfee, paysucessdate, sign);

        // 查询payOrder记录
        String payOrderId = out_trade_no;
        PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
        if (payOrder == null) {
            _log.error("Can't found payOrder form db. payOrderId={}, ", payOrderId);
            return null;
        }

        YipayConfig lfpayConfig = new YipayConfig(getPayParam(payOrder));
        // 验证签名
        Map<String, Object> paramMap = new HashMap();
        paramMap.put("trade_no", trade_no);
        paramMap.put("out_trade_no", out_trade_no);
        paramMap.put("total_fee", total_fee);
        paramMap.put("tradingfee", tradingfee);
        paramMap.put("paysucessdate", paysucessdate);

        String signValue = YipayUtils.getSign(paramMap, lfpayConfig.getKey());
        if(!sign.equals(signValue)) {
            _log.error("验证签名失败. payOrderId={}, ", payOrderId);
            return null;
        }

        payContext.put("queryId", trade_no);
        return payOrder;
    }

}
